import {
  getInspectStandardByPage,
  addInspectStandard,
  updateInspectStandard,
  delInspectStandard,
  exportInspectStandard,
} from '@/services/device/inspectStandard';
import { PlusOutlined } from '@ant-design/icons';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import {
  message,
  Modal,
  Tree,
  Button,
  Cascader,
  Checkbox,
  DatePicker,
  Form,
  Input,
  InputNumber,
  Radio,
  Select,
  Slider,
  Switch,
  TreeSelect,
  Upload,
} from 'antd';
import { sortTran, filterTran } from '@/utils/requestUtil';
import React, { useEffect, useRef, useState } from 'react';
import { ModalForm, ProFormText } from '@ant-design/pro-components';
const InspectStandardSearch: React.FC<{}> = (props) => {
  const actionRef = useRef<ActionType>();
  const [modalVisit, setModalVisit] = useState(false); // 新建和编辑提示框
  const [confirmLoading, setConfirmLoading] = useState(false); //编辑框的disable
  const [formTitle, setFormTitle] = useState('新建'); //
  const [createOrUpdate, setCreateOrUpdate] = useState(false); //编辑框的disable
  const [form] = Form.useForm();
  const ref = useRef(null);
  /* 巡检模板是否上传附件颜色tag组件 */
  const IsAttachedColorTag = ({ text }) => {
    const tagStyle = {
      textAlign: 'center',
      width: '50px',
      height: '27px',
      padding: '5px',
      borderRadius: '3px',
      color: 'white',
      fontSize: '10px',
      backgroundColor: '#13c2c2',
    };
    if (text === '上传') {
      tagStyle.backgroundColor = '#13c2c2';
    } else {
      tagStyle.backgroundColor = '#DC6C76';
    }
    return <div style={tagStyle}>{text}</div>;
  };
  /* 巡检模板有效标记颜色tag组件 */
  const IsValidColorTag = ({ isBlue, text }) => {
    const tagStyle = {
      textAlign: 'center',
      width: '50px',
      height: '27px',
      padding: '5px',
      borderRadius: '3px',
      color: 'white',
      fontSize: '10px',
      backgroundColor: '#13c2c2',
    };
    if (isBlue) {
      tagStyle.backgroundColor = '#13c2c2';
    } else {
      tagStyle.backgroundColor = '#DC6C76';
    }
    return <div style={tagStyle}>{text}</div>;
  };
  const columns: ProColumns[] = [
    {
      title: '序号',
      dataIndex: 'index',
      align: 'center',
      sorter: true,
      valueType: 'index',
      width: 80,
    },
    {
      title: '检查描述',
      align: 'center',
      sorter: true,

      dataIndex: 'checkDesc',
    },
    {
      title: '检查项目',
      align: 'center',
      sorter: true,

      dataIndex: 'checkItem',
    },
    {
      title: '是否需要附件',
      align: 'center',
      sorter: true,

      dataIndex: 'isAttached',
      render: (text: string) => <IsAttachedColorTag text={text} />,
    },
    {
      title: '是否有效',
      align: 'center',
      sorter: true,

      dataIndex: 'isValid',
      render: (text: boolean) => <IsValidColorTag isBlue={text} text={text ? '有效' : '无效'} />,
    },
    // {
    //   title: '顺序编号',
    //   dataIndex: 'sequence',
    // },

    // {
    //   title: '唯一标识',
    //   dataIndex: 'identification',
    // },

    // {
    //   title: '备注',
    //   dataIndex: 'notes',
    // },

    // {
    //   title: '模板编号',
    //   dataIndex: 'templateid',
    // },
    {
      title: '创建日期', //表头显示的名称
      search: false,
      align: 'center',
      sorter: true,

      dataIndex: 'createTime',
    },
    {
      title: '创建人', //表头显示的名称
      search: false,
      align: 'center',
      sorter: true,

      dataIndex: 'createName',
    },
    {
      title: '操作',
      valueType: 'option',
      key: 'option',
      fixed: 'right',
      render: (text, record, _, action) => [
        <a
          key="editKey"
          onClick={() => {
            setModalVisit(true);
            setCreateOrUpdate(true);
            setFormTitle('编辑');
            form.setFieldsValue({
              checkDesc: record.checkDesc,
              checkItem: record.checkItem,
              identification: record.identification,
              isAttached: record.isAttached,
              isValid: record.isValid,
              notes: record.notes,
              sequence: record.sequence,
              templateid: record.templateid,
              id: record.id,
            });
          }}
        >
          编辑
        </a>,
        <a
          key="deleteKey"
          onClick={() => {
            Modal.confirm({
              title: '删除',
              content: '确定要删除吗',
              okText: '确认',
              cancelText: '取消',
              onOk: async () => {
                await delInspectStandard({ id: record.id });
                actionRef.current.reload();
              },
            });
          }}
        >
          删除
        </a>,
      ],
    },
  ];
  const handleSubmit = async (values) => {
    setConfirmLoading(true);
    if (formTitle == '新建') {
      const result = await addInspectStandard(values);
      if (result != null) {
        message.success('添加成功');
      }
    } else {
      await updateInspectStandard(values);
    }
    setConfirmLoading(false);
    setModalVisit(false);
    actionRef.current.reload();
  };

  return (
    <PageHeaderWrapper title={false} breadcrumb={undefined}>
      <ProTable
        headerTitle="巡检详细查询"
        actionRef={actionRef} //用于触发刷新操作等，看api
        rowKey="id" //表格行 key 的取值，可以是字符串或一个函数
        formRef={ref}
        toolBarRender={(action, { selectedRows }) => [
          <Button
            key="button"
            icon={<PlusOutlined />}
            onClick={() => {
              setCreateOrUpdate(false);
              setFormTitle('新建');
              form.resetFields();
              setModalVisit(true);
            }}
            type="primary"
          >
            新建
          </Button>,
          <Button
            key="button"
            icon={<PlusOutlined />}
            onClick={() => {
              const filters = filterTran(ref.current.getFieldsValue());
              exportInspectStandard({
                current: 1,
                pageSize: 5000,
                filters: filters,
              }).then((res) => {
                const aLink = document.createElement('a');
                document.body.appendChild(aLink);
                aLink.style.display = 'none';
                aLink.href = window.URL.createObjectURL(res);
                aLink.setAttribute('download', `InspectStandard.xlsx`);
                aLink.click();
                document.body.removeChild(aLink);
              });
            }}
            type="primary"
          >
            导出
          </Button>,
        ]}
        request={async (params = {}, sort, filter) => {
          if (props.inspectTemplateId === undefined) {
            return {
              data: undefined,
            };
          }
          const sorters = sortTran(sort);
          const filters = [
            {
              andOr: 'and',
              field: 'templateId',
              operator: 'eq',
              value: '1',
            },
          ];
          const result = await getInspectStandardByPage({
            ...params,
            sorters: sorters,
            filters: filters,
          });
          // console.log('传入巡检计划详细id：', props.inspectPlanId);
          console.log('通过id获取巡检计划详细工作项:', result);
          return {
            data: result.data.content,
            total: result.data.totalElements,
            success: result.success,
          };
        }}
        columns={columns}
        scroll={{ x: 2000, y: 350 }}
        rowSelection={{}}
      />

      <ModalForm
        visible={modalVisit}
        title={formTitle}
        form={form}
        onFinish={handleSubmit}
        modalProps={{
          destroyOnClose: true,
          onCancel: () => {
            setModalVisit(false);
          },
        }}
      >
        <ProFormText name="id" label="id" placeholder="请输入名称" hidden={true} />
        <Form.Item name="checkDesc" label="检查描述">
          <Input />
        </Form.Item>
        <Form.Item name="isAttached" label="是否需要上传附件">
          <Radio.Group>
            <Radio value="上传"> 上传 </Radio>
            <Radio value="不上传"> 不上传 </Radio>
          </Radio.Group>
        </Form.Item>
        <Form.Item name="isValid" label="是否有效">
          <Radio.Group>
            <Radio value="true"> 有效 </Radio>
            <Radio value="false"> 无效 </Radio>
          </Radio.Group>
        </Form.Item>
        <Form.Item name="sequence" label="顺序编号">
          <Input />
        </Form.Item>
      </ModalForm>
    </PageHeaderWrapper>
  );
};
export default InspectStandardSearch;
